package com.yx.frame.util;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.yx.frame.service.ServiceResult;

public final class Format {

	public Format() {

	}

	public static ServiceResult convertServiceResult(List<int[]> list)
			throws Exception {
		ServiceResult serviceResult = new ServiceResult();
		int len = list.size();
		JSONArray listResout = new JSONArray();
		for (int i = 0; i < len; i++) {
			int[] data = list.get(i);
			JSONArray row = new JSONArray();
			for (int j = 0; j < data.length; j++) {
				row.put(data[j]);
			}
			listResout.put(row);
		}
		serviceResult.put("Result", listResout);
		return serviceResult;
	}

	public static String roundStr(double d) {
		double rD = round(d, 2);
		DecimalFormat df = new DecimalFormat();
		String rS = df.format(rD);
		// rS = rS.replaceAll(",", "");
		return rS;
	}

	public static double round(double d, int i) {
		double result = 0.0;
		long intNumber = Math.round(d * Math.pow(10, i));
		result = intNumber / Math.pow(10, i);
		return result;
	}

	public static double round(double d) {
		return round(d, 2);
	}

	public static Date formatDate(String date) {
		if(date==null||"".equals(date)||"null".equals(date)||date.length()<10)return null;		
		if(date.length()>10)date=date.substring(0,10);
	    return formatDate(date, "yyyy-MM-dd");
	}

	public static Date formatDate(String date, String format) {
		if (date == null)
			return null;
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			return sdf.parse(date);
		} catch (Exception e) {
			return null;
		}
	}

	public static String parseDate(Date d) {
		return parseDate(d, "yyyy-MM-dd");
	}

	public static String parseDate(Date d, String format) {
		if (d == null)
			return null;
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			return sdf.format(d);
		} catch (Exception e) {
			return null;
		}
	}

	public static void sort(Object[] a, int[] idxArray) {
		Object[] aux = (Object[]) a.clone();
		int[] auxIdxArray = (int[]) idxArray.clone();
		mergeSort(aux, a, auxIdxArray, idxArray, 0, a.length, 0);
	}

	private static void mergeSort(Object[] src, Object[] dest,
			int[] srcidxArray, int[] descidxArray, int low, int high, int off) {
		int length = high - low;
		for (int i = low; i < high; i++)
			for (int j = i; j > low
					&& ((Comparable) dest[j - 1]).compareTo(dest[j]) > 0; j--)
				swap(dest, descidxArray, j, j - 1);
		return;
	}

	private static void swap(Object[] x, int[] idxArray, int a, int b) {
		Object t = x[a];
		x[a] = x[b];
		x[b] = t;

		int idxTmp = idxArray[a];
		idxArray[a] = idxArray[b];
		idxArray[b] = idxTmp;
	}

}
